package cn.dengta.webapp.trade.dao;

import java.util.List;

import cn.dengta.webapp.base.dao.BaseDao;
import cn.dengta.webapp.trade.entity.UserIntimacy;
import org.apache.ibatis.annotations.*;

public interface UserIntimacyDao extends BaseDao<UserIntimacy> {

	@Insert("""
			INSERT INTO dt_user_intimacy(low_user_id,high_user_id,score,add_time, update_time) VALUES (#{lowUserId}, #{highUserId}, #{score}, NOW(3),NOW(3))
			ON DUPLICATE KEY UPDATE score = #{score}, update_time = NOW(3)
			""")
	Integer addUserScore(@Param("lowUserId") Long lowUserId, @Param("highUserId") Long highUserId, @Param("score") Integer score);

	@Select("""
			SELECT if(low_user_id = #{userId},high_user_id, low_user_id) AS low_user_id, score FROM dt_user_intimacy 
			WHERE (low_user_id = #{userId} AND high_user_id ${toUserIds}) OR (high_user_id = #{userId} AND low_user_id ${toUserIds})
			""")
	List<UserIntimacy> findByUserIds(@Param("userId") Long userId, @Param("toUserIds") String toUserIds);

	@SelectProvider(value = UserIntimacyProvider.class, method = "batchInitUserScore")
	Integer batchInitUserScore(@Param("list") List<UserIntimacy> list);

	public static class UserIntimacyProvider {

		public String batchInitUserScore(@Param("list") List<UserIntimacy> list) {
			StringBuilder sql = new StringBuilder(2048);
			sql.append("INSERT INTO dt_user_intimacy(low_user_id,high_user_id,score,add_time, update_time) VALUES ");
			for (int i = 0; i < list.size(); i++) {
				sql.append("(");
				sql.append("#{list[").append(i).append("].lowUserId}").append(",");
				sql.append("#{list[").append(i).append("].highUserId}").append(",");
				sql.append("#{list[").append(i).append("].score}").append(",");
				sql.append("NOW()").append(",");
				sql.append("NOW()");
				sql.append(")");
				if (i < list.size() - 1) {
					sql.append(",");
				}
			}
			return sql.toString();
		}

	}

}
